package com.xmu.edu.tisp.service.basedata;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.xmu.edu.tisp.dao.Service;
import com.xmu.edu.tisp.dao.TISP_dbHelper;

public class CM_LEAF_VARIETY_service implements Service{
	

	public static final String TABLE_NAME = "CM_LEAF_VARIETY";
	public static final String PRIMARY_KEY="LEAF_VARIETY_UUID";
	
	private SQLiteDatabase myDB;
	private SQLiteOpenHelper dbHelper;


	public CM_LEAF_VARIETY_service(Context cxt) {
		dbHelper=new TISP_dbHelper(cxt, "TISP");
	}

	public SQLiteDatabase getdb()
	{
		if(myDB==null)
		{
			myDB=dbHelper.getWritableDatabase();
			return myDB;
		}
		return myDB;
	}
	
	@Override
	public void g_updata(ContentValues values) {
		getdb().update(TABLE_NAME, values, PRIMARY_KEY+"=?", new String[]{(String) values.get(PRIMARY_KEY)});
		System.out.println(TABLE_NAME+"have updataed!");
		myDB.close();
	}

	@Override
	public void g_insert(ContentValues values) {
		getdb().insert(TABLE_NAME, null, values);
		myDB.close();
		System.out.println(TABLE_NAME+"have inserted!");
	}

	@Override
	public void g_delete(String[] id) {
		getdb().delete(TABLE_NAME, PRIMARY_KEY+"=?", id);
		System.out.println(TABLE_NAME+"have deleted!");
		myDB.close();
	}


	@Override
	public List<String> g_getIDs() {
		Cursor c=getdb().query(TABLE_NAME, new String[]{PRIMARY_KEY},null, null, null, null, null);
		List<String> result=new ArrayList<String>();
		while(c.moveToNext())
		{
			String id=c.getString(c.getColumnIndex(PRIMARY_KEY));
			result.add(id);
		}
		return result;
	}
	
	public Cursor fetchAllData(){
		//System.out.println("111111111111111111111111111");
		Cursor cursor=getdb().rawQuery("select LEAF_VARIETY_UUID,LEAF_TYPE_NAME,LEAF_VARIETY_CD,LEAF_VARIETY_NAME  " + 
				"from CM_LEAF_TYPE,CM_LEAF_VARIETY " + 
				"where CM_LEAF_TYPE.LEAF_TYPE_UUID=CM_LEAF_VARIETY.LEAF_TYPE_UUID ;"
				, null);
		//System.out.println("1111111111444444");
        cursor.deactivate();
        return cursor;
	}
	
	public Cursor fetchDataByCD(String LEAF_VARIETY_CD){
		System.out.println(LEAF_VARIETY_CD);
		Cursor cursor=getdb().rawQuery("select *  " + 
				"from CM_LEAF_VARIETY " + 
				"where LEAF_VARIETY_CD=?;"
				, new String [] {LEAF_VARIETY_CD});
		//System.out.println("1111111111444444");
        cursor.deactivate();
        return cursor;
	}

}
